package com.study.common;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * bean工具类
 *
 * @author lemontree
 * @version 2.0, 2017/7/4
 * @since 2.0
 *
 * modify by huangzy
 * add copyProperties(Object orig, Class<T> clz) /copyPropertiesList(Class<T> clz, List<?> origList)
 * date:2017/09/08
 */
public class BeanUtils {
    private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    private static BeanUtilsBean beanUtilsBean = new BeanUtilsBean(){
        @Override
        public void copyProperty(Object dest, String name, Object value)
                throws IllegalAccessException, InvocationTargetException {
            // 为空或不作任务拷贝动作
            if (Objects.isNull(value)) {
                return;
            }

            super.copyProperty(dest, name, value);
        }
    };


    /**
     * 属性拷贝，会对类型不匹配的属性和空值做过滤
     *
     * @param dest 待被拷贝对象
     * @param orig 有数据目标对象
     */
    public static void copyProperties(Object dest, Object orig) {
        try {
            beanUtilsBean.copyProperties(dest, orig);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * 属性拷贝，会对类型不匹配的属性和空值做过滤
     *
     * @param clz 待被拷贝类型
     * @param orig 有数据目标对象
     * @param orig
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> T copyProperties(Class<T> clz,Object orig) {
        try {
            Object dest = clz.newInstance();
            beanUtilsBean.copyProperties(dest, orig);
            return (T)dest;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> copyPropertiesList(Class<T> clz, List<?> origList) {
        return origList.stream().map(o -> copyProperties(clz,o)).collect(Collectors.toList());
    }
}
